
package com.axc.gallery2.album;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.axc.gallery2.R;
import com.axc.gallery2.ThemeChoice;
import com.axc.gallery2.Utils;
import com.axc.gallery2.dbhelper.AlbumDBHelper;
import com.axc.gallery2.dbhelper.AlbumInfo;
import com.axc.gallery2.dbhelper.DBInfo;
import com.axc.gallery2.dbhelper.ImageInfo;
import com.axc.gallery2.dbhelper.ImagesDBhelper;
import com.axc.gallery2.dbhelper.NetAlbumDHhelper;
import com.axc.gallery2.menu.RootMenu;
import com.axc.gallery2.net.activity.NetAlbumsActivity;
import com.axc.gallery2.view.AlbumAdapter;
import com.axc.gallery2.view.GalleryProgressDialog;
import com.axc.gallery2.view.GridViewActivity;

/**
 * 相册应用首页
 *
 */
public class AlbumListViewActivity extends Activity {

	private ListView listView;
	private View listViewItem;
	private EditText albumNameView;
	private EditText albumDrView;
	// 设置菜单
	private final int MENUADD = 1;
	private final int MENUDEL = 2;
	private final int MENUOPEN = 3;
	private final int MENUEDIT = 4;
	private final int MENUCANCEL = 5;
	private final int MENUADDIMAGES = 6;
	private final int MENUUPDATE = 7;
	// 终止方法执行
	private boolean isStop = false;
	// 对话框
	private final int DIALOGADD = 0;
	private final int DIALOGEDIT = 1;
	private AlertDialog alertDialog = null;
	// 相册id
	private int albumId = 0;
	private AlbumAdapter adapter;
	private AlbumDBHelper albumDBHelper;
	// 对话框
	private GalleryProgressDialog gProgressDialog = null;

	// 程序第一次运行
	private boolean firstRun;

	//头部菜单容器
	private LinearLayout menuhead=null;

	//主题应用
	public static AlbumListViewActivity Talbum;
	public int theme = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 主题
		Talbum = this;
		theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
				android.R.style.Theme);
		setTheme(theme);

		super.onCreate(savedInstanceState);
		// 设置不显示标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		LinearLayout line = new LinearLayout(this);
		line.setOrientation(LinearLayout.VERTICAL);
		// 添加菜单
		RootMenu rootmenu = new RootMenu(this);
		rootmenu.initView();// 初始化菜单
		try {
			rootmenu.iniOnClickListener();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		// 初始化子菜单单击事件
		line.addView(rootmenu);

		View view = LayoutInflater.from(this)
				.inflate(R.layout.album_listview, null);
		line.addView(view);
		// 设置布局
		setContentView(line);

		//头部菜单样式随着主题改变
		menuhead=(LinearLayout)findViewById(R.id.layoutContent);
		new Utils().setMenuBackGround(menuhead, theme);

		// 获取列表
		listView = (ListView) findViewById(R.id.albumlistview);
		// 设置listview
		iniListview();
		// 显示Dialog
		albumDBHelper = new AlbumDBHelper(this);
		gProgressDialog = new GalleryProgressDialog(this) {

			@Override
			public void setRun() {
				// 首次运行
				firstLoad();
				// 加载相册
				addAlbums();
			}
		};
		// 获取程序是否第一次运行
		firstRun = albumDBHelper.getIsFirstRun();
		if (firstRun) {
			gProgressDialog.setTitle(R.string.firstrun);
			gProgressDialog.setButton(getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					isStop = true;
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					gProgressDialog.dismiss();
				}

			});
		}
		gProgressDialog.setHandler(new Handler() {
			public void handleMessage(Message msg) {

				// 显示相册
				adapter.notifyDataSetChanged();
				gProgressDialog.dismiss();
			}
		});
		// 显示对话框
		gProgressDialog.showGalleryProgressDialog();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*
		 * switch (item.getItemId()) { case 0: if( R.style.BlueTheme != theme ){
		 * Talbum.getSharedPreferences("cons",Activity.MODE_PRIVATE).edit()
		 * .putInt("theme", R.style.BlueTheme).commit(); Intent intent = new
		 * Intent(); intent.setClass(AlbumListViewActivity.this,
		 * ThemeChoice.class); startActivity(intent);
		 * android.os.Process.killProcess(android.os.Process.myPid()); } break;
		 * case 1: if( R.style.WhiteTheme != theme ){
		 * Talbum.getSharedPreferences("cons",Activity.MODE_PRIVATE).edit()
		 * .putInt("theme", R.style.WhiteTheme).commit(); Intent intent = new
		 * Intent(); intent.setClass(AlbumListViewActivity.this,
		 * ThemeChoice.class); startActivity(intent);
		 * android.os.Process.killProcess(android.os.Process.myPid()); } break;
		 * case 2: Toast.makeText(AlbumListViewActivity.this, "2",
		 * Toast.LENGTH_SHORT).show(); break; case 3:
		 * Toast.makeText(AlbumListViewActivity.this, "3",
		 * Toast.LENGTH_SHORT).show(); break; }
		 */
		Intent intent = new Intent();
		intent.setClass(AlbumListViewActivity.this, ThemeChoice.class);
		startActivity(intent);
		this.finish();
		return true;
	}

	// 进程的调用
	public void goIntent(Intent intent, Class<?> cls) {
		intent = new Intent();
		intent.setClass(AlbumListViewActivity.this, cls);
		startActivity(intent);
	}

	// 设置按钮（主题）
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		int base = Menu.FIRST;
		// 一个menu可以包括多个子菜单
		menu.addSubMenu(base, 11, Menu.NONE, "主题设置");
		// 子菜单可以包括多个菜单项
		/*
		 * MenuItem menuitem1 = subMenu.add(base,0, base+1, "魅力蓝色");
		 * subMenu.add(base,1, base+2, "玫瑰红色"); subMenu.add(base,2, base+3,
		 * "高雅淡黄"); subMenu.add(base,3, base+4, "婚纱世界");
		 */

		// 子菜单项不支持显示图标，这样做是没意义的，尽管不会报错！
		// menuitem1.setIcon(R.drawable.displaysettings);

		// 但是子菜单本身是支持图标的
		// subMenu.setIcon(R.drawable.settings);

		// 显示菜单请返回true
		return true;
	}

	// 显示相册
	public void iniListview() {
		adapter = new AlbumAdapter(this, new ArrayList<AlbumInfo>());
		listView.setAdapter(adapter);
		AlbumListViewActivity.this.registerForContextMenu(listView);
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View v,
					int arg2, long arg3) {
				albumId = Integer.valueOf(((TextView) v.findViewById(R.id.txtAlbumID)).getText()
						.toString());
				System.out.println("index:" + albumId);

				return false;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				albumId = Integer.valueOf(((TextView) view.findViewById(R.id.txtAlbumID)).getText()
						.toString());
				System.out.println("index:" + albumId);
				callIntent();
			}
		});
		listView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				System.out.println("motionEvent:" + motionEvent.getAction());
				if (motionEvent.getAction() == MotionEvent.EDGE_LEFT) {
					albumId = Integer.valueOf(((TextView) view.findViewById(R.id.txtAlbumID))
							.getText().toString());

					callIntent();
				}
				return false;
			}
		});
	}

	/**
	 * 初始化上下文菜单 每次调出上下文菜单时都会被调用一次
	 */
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.setHeaderIcon(R.drawable.ic_launcher);
		menu.add(0, MENUOPEN, 0, R.string.album_menu_open);
		menu.add(0, MENUADD, 0, R.string.album_menu_add);
		menu.add(0, MENUADDIMAGES, 0, R.string.album_menu_addimages);
		menu.add(0, MENUEDIT, 0, R.string.album_menu_edit);
		menu.add(0, MENUDEL, 0, R.string.album_menu_dele);
		menu.add(0, MENUUPDATE, 0, R.string.album_menu_update);
		menu.add(0, MENUCANCEL, 0, R.string.cancel);
		// 不能修改本地相册,网络相册,及系统相册信息
		if (albumId == AlbumInfo.LOCALALBUMID || albumId == AlbumInfo.NETALBUMID
				|| albumId == AlbumInfo.PHONEALBUMID) {
			menu.findItem(MENUDEL).setEnabled(false);
			menu.findItem(MENUEDIT).setEnabled(false);
			menu.findItem(MENUADDIMAGES).setEnabled(false);
		}
	}

	// 首次运行程序
	public void firstLoad() {
		if (firstRun) {// 判断是否是第一次允许程序
			// 创建相册
			System.out.println("创建相册");
			// 添加网络图片
			albumDBHelper.addAlbum(getString(R.string.album_net), getString(R.string.album_netdr));
		}
	}

	// 显示相册
	private void addAlbums() {
		// 系统图片添加
//		System.out.println("==========系统图片===============");
//		System.out.println(Environment.getRootDirectory().getPath());
//		List<String> phoneList = this.getPictures("system/", 0);
//		adapter.add(new AlbumInfo(AlbumInfo.PHONEALBUMID, getString(R.string.album_phone),
//				getString(R.string.album_phonedr), phoneList));
//		System.out.println("==========系统图片===============" + phoneList.size());
//		System.out.println(Environment.getExternalStorageDirectory().getPath()
//				+ "/DCIM/Camera"
//				+ "ise:"
//				+ new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera")
//		.exists());

		
		//        List<String> locationList = this.getPictures(Environment.getExternalStorageDirectory()
		//                .getPath()
		//                + "/DCIM", 1);
		//        // 添加SD图片
		//        adapter.add(new AlbumInfo(AlbumInfo.LOCALALBUMID, getString(R.string.album_location),
		//                getString(R.string.album_locationdr), locationList));
		//        for (AlbumInfo a : albumDBHelper.getAlbums()) {
		//            System.out.println("=========================");
		//            System.out.println("albumInfoadd" + a.getAlbumId() + a.getAlbumName()
		//                    + a.getDescription() + "size:" + a.getAlbumItems().size());
		//            System.out.println("=========================");
		//            adapter.add(a);
		//        }
		ContentResolver cr = getContentResolver();
		String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID, Thumbnails.DATA };
		Cursor cursor = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);
		List<ImageInfo> lImageInfos= getColumnData(cursor);//获取图片缩略图
		AlbumInfo aInfo=new AlbumInfo(AlbumInfo.PHONEALBUMID, getString(R.string.album_phone),
				getString(R.string.album_phonedr), lImageInfos);
		// 取实际图片的方法
		String columns[] = new String[] { Media.DATA, Media._ID, Media.TITLE, Media.DISPLAY_NAME, Media.SIZE };  
		// 得到一个游标  
		Cursor cursor2 = this.getContentResolver().query(Media.EXTERNAL_CONTENT_URI, columns, null, null, null);   
		
		// 获取图片总数  
		aInfo.AlbumInfo_Count = cursor2.getCount(); 
		adapter.add(aInfo);
		cursor2.close();
		//网络相册
		NetAlbumDHhelper netAlbumDHhelper = new NetAlbumDHhelper(this);
		List<ImageInfo> tempList = new ArrayList<ImageInfo>();
		for (int i = 0; i < netAlbumDHhelper.getNetAlbums().size(); i++) {
			tempList.add(new ImageInfo());
		}
		adapter.getAlbum(DBInfo.NetAlbumID).setAlbumItems(tempList);
	}

	private List<ImageInfo> getColumnData(Cursor cur) {
		List<ImageInfo> list=new ArrayList<ImageInfo>();
		if (cur.moveToFirst()) {
			int image_id;
			String image_path;
			int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);
			int dataColumn = cur.getColumnIndex(Thumbnails.DATA);

			do {

				image_id = cur.getInt(image_idColumn);
				image_path = cur.getString(dataColumn);
				ImageInfo imageInfo=new ImageInfo();
				imageInfo.image_id=image_id+"";
				imageInfo.image_path=image_path;
				list.add(imageInfo);

			} while (cur.moveToNext()||cur.getPosition()<20);
			cur.close();
		}
		return list;
	}
	// 跳转activity
	private void callIntent() {
		Intent intent = new Intent();
		if (albumId == DBInfo.NetAlbumID) {
			intent.setClass(AlbumListViewActivity.this, NetAlbumsActivity.class);
			AlbumListViewActivity.this.startActivity(intent);
		} else {

			AlbumInfo aInfo = adapter.getAlbum(albumId);
			intent.setClass(AlbumListViewActivity.this, GridViewActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable(AlbumInfo.SERALIZABLEKEY, aInfo);
			// bundle.putParcelable(AlbumInfo.SERALIZABLEKEY,aInfo);
			intent.putExtras(bundle);
			AlbumListViewActivity.this.startActivityForResult(intent, 0);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println("onActivityResult:" + requestCode + "\t" + resultCode);
		switch (resultCode) {
		case RESULT_OK:
			adapter.clearConvaerView();
			adapter.getAlbums().clear();
			addAlbums();
			adapter.notifyDataSetChanged();
			break;
		}
	}

	/**
	 * 当用户选择了上下文菜单选项后调用该事件
	 */
	public boolean onContextItemSelected(MenuItem item) {
		;
		switch (item.getItemId()) {
		case MENUOPEN:// 打开相册
			callIntent();
			break;
		case MENUADD:// 添加相册
			showDialog(DIALOGADD);
			break;
		case MENUEDIT:// 修改相册
			showDialog(DIALOGEDIT);
			break;
		case MENUDEL:// 删除相册
			System.out.println("/删除相册:" + albumId + "name:"
					+ adapter.getAlbum(albumId).getAlbumName());
			albumDBHelper.delAlbum(albumId);
			adapter.removeAt(albumId);
			Toast.makeText(AlbumListViewActivity.this, R.string.album_delsuccess,
					Toast.LENGTH_LONG).show();

			break;
		case MENUADDIMAGES:// 添加图片
			albumId = AlbumInfo.LOCALALBUMID;
			callIntent();
			break;
		case MENUUPDATE:// 更新相册
			alertDialog = new AlertDialog.Builder(this).setTitle(R.string.dialogtitle)
			.setMessage(R.string.album_dialog_updatemessage)
			.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					alertDialog.dismiss();
					final GalleryProgressDialog galleryProgressDialog = new GalleryProgressDialog(
							AlbumListViewActivity.this) {

						@Override
						public void setRun() {
							ImagesDBhelper imagesDBhelper = new ImagesDBhelper(
									getBaseContext());
							imagesDBhelper.checkImages();
							adapter.getAlbums().clear();
							addAlbums();
						}
					};
					galleryProgressDialog.setButton(getString(R.string.cancel),
							new OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							isStop = true;
							try {
								Thread.sleep(50);
							} catch (InterruptedException e) {

								e.printStackTrace();
							}
							// 加载相册
							adapter.getAlbums().clear();
							addAlbums();
							galleryProgressDialog.dismiss();
						}

					});
					galleryProgressDialog.setHandler(new Handler() {

						@Override
						public void handleMessage(Message msg) {
							isStop = false;
							adapter.notifyDataSetChanged();
							galleryProgressDialog.dismiss();
						}
					});
					galleryProgressDialog.showGalleryProgressDialog();

				}
			})
			.setNegativeButton(R.string.cancel, null).create();
			alertDialog.show();
			break;
		}

		return true;

	}

	// 创建对话框
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		// 获取列表项
		if (listViewItem == null) {
			listViewItem = LayoutInflater.from(this)
					.inflate(R.layout.album_listview_edititem, null);
			albumNameView = (EditText) listViewItem.findViewById(R.id.editTextAlbumName);
			albumDrView = (EditText) listViewItem.findViewById(R.id.editTextViewAlbumDr);
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(AlbumListViewActivity.this)
		.setTitle(R.string.album_addtitle).setView(listViewItem)
		.setIcon(android.R.drawable.ic_dialog_info)
		.setNegativeButton(R.string.cancel, new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				albumNameView.setText("");
				albumDrView.setText("");
				alertDialog.dismiss();

			}
		});
		switch (id) {
		// 添加相册
		case DIALOGADD:
			alertDialog = builder.setPositiveButton(R.string.sure, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						if (!albumNameView.getText().toString().equals("")) {
							albumDBHelper.addAlbum(albumNameView.getText().toString(),
									albumDrView.getText().toString());
							System.out.println("AlbumListViewActivity.onCreateDialog()");
							System.out.println("albumDBHelper.getMaxId():"
									+ albumDBHelper.getMaxId() + "albumNameView:"
									+ albumNameView.getText());
							adapter.add(new AlbumInfo(albumDBHelper.getMaxId(), albumNameView
									.getText().toString(), albumDrView.getText().toString(),
									new ArrayList<ImageInfo>()));
							albumNameView.setText("");
							albumDrView.setText("");
							adapter.notifyDataSetChanged();

						} else {
							Toast.makeText(getBaseContext(), R.string.album_addname,
									Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						Toast
						.makeText(getBaseContext(),
								R.string.album_addexception + e.getMessage(),
								Toast.LENGTH_LONG).show();
					}

				}
			}).create();
			break;
			// 修改相册
		case DIALOGEDIT:
			// 获取相册信息
			albumNameView.setText(adapter.getAlbum(albumId).getAlbumName());
			albumDrView.setText(adapter.getAlbum(albumId).getDescription());
			alertDialog = builder.setPositiveButton(R.string.album_menu_edit,
					new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					AlbumInfo albumInfo = adapter.getAlbum(albumId);
					albumInfo.setAlbumName(albumNameView.getText().toString());
					albumInfo.setDescription(albumDrView.getText().toString());
					adapter.editItem(albumId, albumInfo);
					albumDBHelper.updateAlbum(albumId, albumNameView.getText()
							.toString(), albumDrView.getText().toString());
					Toast.makeText(getBaseContext(), R.string.album_editsuccess,
							Toast.LENGTH_LONG).show();
				}
			}).create();

			break;
		default:
			alertDialog = null;
			break;
		}
		return alertDialog;

	}

	static List<String> PicturesList = new ArrayList<String>();
	static List<String> PicturesListSystem = new ArrayList<String>();

	/**
	 * 获取图片
	 * 
	 * @param strPath 路径
	 *@param location 0 为系统图片，1为所有图片
	 */
	public List<String> getPictures(final String strPath, int location) {
		// PicturesList可能存放有上一次的结果，有则清空
		if (PicturesList.size() > 0) {
			PicturesList.clear();
		}
		searchPictures(strPath, location);

		if (location == 0) {
			return PicturesListSystem;
		}
		return PicturesList;
	}

	// 遍历文件夹内所有图片（包括子文件夹）：递归调用
	private void searchPictures(final String strPath, int location) {

		File file = new File(strPath);
		File[] files = file.listFiles();

		if (files == null) {
			return;
		}

		for (int i = 0; i < files.length; i++) {
			if (isStop) {
				isStop = false;
				return;
			}
			final File f = files[i];
			if (f.isFile()) {
				try {
					int idx = f.getPath().lastIndexOf(".");
					if (idx <= 0) {
						continue;
					}
					String suffix = f.getPath().substring(idx);
					if (suffix.toLowerCase().equals(".jpg") ||
							suffix.toLowerCase().equals(".jpeg") ||
							suffix.toLowerCase().equals(".bmp") ||
							suffix.toLowerCase().equals(".png") ||
							suffix.toLowerCase().equals(".gif")) {
						if (location == 0) {
							PicturesListSystem.add(f.getPath());
						} else {
							PicturesList.add(f.getPath());
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			} else {
				searchPictures(f.getPath(), location);
				System.out.println(f.getPath());
			}
		}
	}

	// 侦听用户的点击返回键,提示程序退出
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			dialog();
			return true;
		}
		return false;
	}

	protected void dialog() {
		AlertDialog.Builder builder = new Builder(AlbumListViewActivity.this);
		builder.setMessage(R.string.exitmsg);
		builder.setTitle(R.string.tiptitle);
		builder.setPositiveButton(R.string.ok,
				new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				// AlbumListViewActivity.this.finish();
				//System.exit(0);
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		builder.setNegativeButton(R.string.cancel,
				new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
}
